package com.caldremch.androidfoundation.http;

import android.accounts.NetworkErrorException;

import com.caldremch.androidfoundation.http.callback.AbsCallback;
import com.caldremch.androidfoundation.http.model.BaseRespData;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import io.reactivex.observers.DisposableObserver;

/**
 *  user for unsubscribe  && all the exception handle
 * @param <T> type
 */
public  class ApiObserver<T>  extends DisposableObserver<BaseRespData<T>> {



    private AbsCallback<T>  mCallback;


    public ApiObserver(AbsCallback<T> mCallback) {
        this.mCallback = mCallback;
    }

    // 1.是否弹 toast
    // 2.是否开启 dialog

    private boolean mToastEnable;


    @Override
    public void onNext(BaseRespData<T> t) {

        //处理 toast
        handleToast(t);

        //结果返回
        if (t.code != 0) {
            //错误回调
            try {

                if (mCallback != null) {
                    mCallback.onFailure(t, null);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {

            //成功回调
            try {
                if (mCallback != null) {
                    mCallback.onSuccess(t, t.data);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }




    }

    private void handleToast(BaseRespData<T> t) {
        if (t.code != 0) {
            //在这里也可以处理特殊的 code 是否需要弹出
            if (mToastEnable) {
                // TODO: 2018/9/3 吐司
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        //错误返回
        try {
            if (e instanceof ConnectException || e instanceof TimeoutException || e instanceof NetworkErrorException || e instanceof UnknownHostException) {
                //网络错误, 特殊处理
                // TODO: 2018/9/3 网络错误的吐司
                if (mCallback != null) {
                    mCallback.onFailure(null, e);
                }

            } else {
                //其他错误
                if (mCallback != null) {
                    mCallback.onFailure(null, e);
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

    }

    @Override
    public void onComplete() {

    }

//    protected abstract void onSuccess(BaseRespData<T> respData, T data) throws Exception;
//    protected abstract void onFailure(BaseRespData<T> respData, Throwable e) throws Exception;



}



